import React from 'react';
import { View, ActivityIndicator } from 'react-native';
import { Overlay } from "../script/_teaset";
import CodePush from "react-native-code-push"
import { Dialog } from "./Dialog"
import { Lt, Jx } from "./Jx"
import { Label } from './Component';
import { Login } from './Login';

// 热更新指示器
class CpushIndicator extends React.Component{
    constructor(props){
        super(props);
        this.state = {percent : 0};
    }
    setPercent(percent, total){
        if(percent == 0){
            return;
        }
        total = total / 100;
        percent =  percent / total;
        percent = parseInt(percent) - 1;
        if(percent < 1){
            return;
        }
        this.setState({percent : percent});
    }
    render(){
        return <View style={{ backgroundColor:"rgba(64, 64, 64, 0.8)", width:"80%", padding:25, borderRadius:15, alignItems:"center"}}>
            <ActivityIndicator size={'large'} animating={true}/>
            <Label style={{ fontSize: Lt.c16, color: "white", textAlign : "center" }}>
                {this.state.percent == 0 ? "下载中..." : ("更新中...\n" + this.state.percent + "%")}
            </Label>
        </View>       
    }
}

// 热更新
export class Cpush {
    static flag_n1_0_1;
    static flag_checked;
    static reset(){
        console.log('重置热更新');
        this.flag_n1_0_1 = -1;
        this.flag_checked = false;
    }
    static check(){
        if(this.flag_n1_0_1 != -1){
            return;
        }
        console.log('检测热更新');
        CodePush.checkForUpdate()
        .then(update=>{
            if(update){
                this.flag_n1_0_1 = 1;
                console.log('有更新');
            } else {
                this.flag_n1_0_1 = 0;
                console.log('无更新');
            }
        }).catch(err=>{
            console.warn("热更新异常: " + Jx.stringify(err));
        })
    }
    static checked(){
        if(this.flag_checked){
            if(this.interval){
                clearInterval(this.interval);
                this.interval = null;
            }
        } else {
            if(this.flag_n1_0_1 == 1){
                this.flag_checked = true;
                if(this.interval){
                    clearInterval(this.interval);
                    this.interval = null;
                }
                Dialog.msg2("新的更新", this.show.bind(this), null, "更新", "稍后");
            }
        }
    }
    static checkedInterval(){
        this.checked();
        this.interval = setInterval(this.checked.bind(this), 700);
    }
    static show(){
        if(this.flag_n1_0_1 == 0){
            Dialog.toast("已最新");
            return;
        }
        Dialog.loading(true);
        let dialog = {
            appendReleaseDescription: true,//是否显示更新description，默认false
            //要显示的更新通知的标题. Defaults to “Update available”.
            title: '',
            //强制更新时，更新通知. Defaults to “An update is available that must be installed.”.
            mandatoryUpdateMessage: '', 
            //强制更新的按钮文字. 默认 to “Continue”.
            mandatoryContinueButtonLabel: '更新',
            //非强制更新时，取消按钮文字. Defaults to “Ignore”.
            optionalIgnoreButtonLabel: "忽略",
            //非强制更新时，确认文字. Defaults to “Install”.
            optionalInstallButtonLabel: "更新",
            //更新说明的前缀。 默认是” Description: “
           // descriptionPrefix: '更新内容：\n', 
            descriptionPrefix: '',
            //非强制更新时，更新通知. Defaults to “An update is available. Would you like to install it?”.
            optionalUpdateMessage: "发现新的更新，您是否要安装最新版本"
        };
        //可选的，更新的对话框，默认是null,包含以下属性
        CodePush.sync({
            updateDialog: dialog,
            //(CodePush.InstallMode)： 安装模式，用在向CodePush推送更新时没有设置强制更新(mandatory为true)的情况下，默认CodePush.InstallMode.ON_NEXT_RESTART即下一次启动的时候安装。
            //installMode :CodePush.InstallMode.ON_NEXT_RESTART
            // (CodePush.InstallMode):强制更新,默认CodePush.InstallMode.IMMEDIATE。
            mandatoryInstallMode: CodePush.InstallMode.IMMEDIATE,
            //指定那个环境下 直接填写key 就行    但是不建议使用 因为 苹果和Android的是分开的 无法做到同时更新 Android 和 IOS
            //deploymentKey: "v-5TDPSESydQj-n9alBgCVEab3Mefdf2b04e-456b-420f-8acd-58a99c8306be",
        }, 
        (status) => {
            switch (status) {
                case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
                console.log("检测呼出对话框");
                break;
            case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
                console.log("下载更新包...");
                this.update(0, 0);
                Login.clearCache();
                break;
            case CodePush.SyncStatus.INSTALLING_UPDATE:
                console.log("热更新...Installing update.");
                break;
            case CodePush.SyncStatus.UP_TO_DATE:
                console.log("热更新...UP_TO_DATE.");
                break;
            case CodePush.SyncStatus.UPDATE_INSTALLED:
                console.log("热更新...UPDATE_INSTALLED");
                break;
            }
        },
        (progress) => {
            // console.log(progress.receivedBytes + " of " + progress.totalBytes + " received.");
            this.update(progress.receivedBytes, progress.totalBytes);
        });
    }

    static update(percent, total) {
        if(!this.updateFlag){
            this.updateFlag = true;
            Dialog.hiding();
            console.log("创建更新指示器");
            Overlay.show(<Overlay.View
                style={{ alignItems: 'center', justifyContent: 'center' }}
                modal={true}
                overlayOpacity={0}>
                <CpushIndicator
                    total = {total}
                    ref={r => this.updatingView = r}
                />
            </Overlay.View>);
        }
        console.log("指示器: " + percent + "/" + total);
        this.updatingView.setPercent(percent, total);
    }
}